﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.IO;

namespace FootBallMatchProject.Piography.Admin
{
    public partial class AddEditClub : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataClassLayer.Club club = new DataClassLayer.Club();
            DataClassLayer.ClubCollection clubs = new DataClassLayer.ClubCollection();
            if (!IsPostBack)
            {
                RefreshCoaches();
                RefreshLeagues();
                RefreshStadiums();
                if (Request.QueryString["operation"] != null &&
                    Request.QueryString["operation"].ToString() == "Edit")
                {
                    pnlStatistics.Visible = true;
                    RefreshList();
                    if (Request.QueryString["id"] != null &&
                    Request.QueryString["id"].ToString() != "")
                    {
                        club.ID = int.Parse(Request.QueryString["id"].ToString());
                        DataTable table = clubs.FillList(club);
                        if (table.Rows.Count == 1)
                        {
                            btnClear.Visible = false;
                            Logo.ImageUrl = "~/images/Club_Logos/" + Request.QueryString["id"].ToString() + "/" + table.Rows[0]["Logo"].ToString();
                            Logo.Visible = true;
                            hfLogo.Value = table.Rows[0]["Logo"].ToString();
                            txtClub.Text = table.Rows[0]["Name"].ToString();
                            dtDateOfFoundation.Text = table.Rows[0]["DateOfFoundation"].ToString();
                            cmbCoaches.SelectedValue = table.Rows[0]["CoachID"].ToString();
                            txtWebSite.Text = table.Rows[0]["OfficialWebSite"].ToString();
                            cmbLeagues.SelectedValue = table.Rows[0]["LeagueID"].ToString();
                            cmbStadiums.SelectedValue = table.Rows[0]["StadiumID"].ToString();
                            txtGeneralInformation.Text = table.Rows[0]["GeneralInformation"].ToString();
                            Color.ImageUrl = "~/images/Club_ColorImages/" + Request.QueryString["id"].ToString() + "/" + table.Rows[0]["ColorImage"].ToString();
                            Color.Visible = true;
                            hfColorImage.Value = table.Rows[0]["ColorImage"].ToString();
                            ClubImage.ImageUrl = "~/images/Club_Images/" + Request.QueryString["id"].ToString() + "/" + table.Rows[0]["Image"].ToString();
                            ClubImage.Visible = true;
                            hfClubImage.Value = table.Rows[0]["Image"].ToString();
                        }
                    }
                }
            }
        }
        private void RefreshCoaches()
        {
            DataClassLayer.Coach coach = new DataClassLayer.Coach();
            DataClassLayer.CoachCollection coaches = new DataClassLayer.CoachCollection();
            DataTable table = coaches.FillList(coach);
            if (table.Rows.Count > 0)
            {
                cmbCoaches.DataSource = table;
                cmbCoaches.DataValueField = "ID";
                cmbCoaches.DataTextField = "Name";
                cmbCoaches.DataBind();
                cmbCoaches.Items.Insert(0, new ListItem("-اختيار-"));
            }
        }
        private void RefreshLeagues()
        {
            DataClassLayer.League league = new DataClassLayer.League();
            DataClassLayer.LeagueCollection leagues = new DataClassLayer.LeagueCollection();
            DataTable table = leagues.FillList(league);
            if (table.Rows.Count > 0)
            {
                cmbLeagues.DataSource = table;
                cmbLeagues.DataValueField = "ID";
                cmbLeagues.DataTextField = "Name";
                cmbLeagues.DataBind();
                cmbLeagues.Items.Insert(0,new ListItem("-اختيار-"));
            }
        }
        private void RefreshStadiums()
        {
            DataClassLayer.Stadium stadium = new DataClassLayer.Stadium();
            DataClassLayer.StadiumCollection stadiums = new DataClassLayer.StadiumCollection();
            DataTable table = stadiums.FillList(stadium);
            if (table.Rows.Count > 0)
            {
                cmbStadiums.DataSource = table;
                cmbStadiums.DataValueField = "ID";
                cmbStadiums.DataTextField = "Name";
                cmbStadiums.DataBind();
                cmbStadiums.Items.Insert(0, new ListItem("-اختيار-"));
            }
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            Response.Redirect("ClubList.aspx");
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string Thump_Name_File = "";
            DataClassLayer.Club club = new DataClassLayer.Club();
            DataClassLayer.ClubCollection clubs = new DataClassLayer.ClubCollection();
            club.Name = txtClub.Text;
            club.DateOfFoundation = DateTime.Parse(dtDateOfFoundation.Text);
            if (cmbCoaches.SelectedIndex != 0 &&
                cmbCoaches.SelectedIndex != -1)
            {
                club.CoachID = int.Parse(cmbCoaches.SelectedValue.ToString());
            }
            else
            {
               //("يجب اختيار المدرب");
                return;
            }
            club.Image = hfClubImage.Value;
            club.OfficialWebSite = txtWebSite.Text;
            club.Logo = hfLogo.Value;
            club.ColorImage = hfColorImage.Value;
            if (cmbLeagues.SelectedIndex != 0 &&
               cmbLeagues.SelectedIndex != -1)
            {
                club.LeagueID = int.Parse(cmbLeagues.SelectedValue.ToString());
            }
            else
            {
               //("يجب اختيار الدوري");
                return;
            }
            club.GeneralInformation = txtGeneralInformation.Text;
            if (cmbStadiums.SelectedIndex != 0 &&
               cmbStadiums.SelectedIndex != -1)
            {
                club.StaduimID = int.Parse(cmbStadiums.SelectedValue.ToString());
            }
            else
            {
               //("يجب اختيار الملعب");
                return;
            }
            if (Request.QueryString["operation"] != null &&
                Request.QueryString["operation"].ToString() == "Edit")
            {
                if (Request.QueryString["id"] != null &&
                              Request.QueryString["id"].ToString() != "")
                {
                    club.ID = int.Parse(Request.QueryString["id"].ToString());
                    bool chkvalue = clubs.Edit(club);
                    if (chkvalue)
                    {
                        if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID())))
                        {
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID()));
                        }
                        string fileName = null;
                        string[] fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_ColorImages"));
                        for (int i = 0; i < fileArray.Length; i++)
                        {
                            fileName = Path.GetFileName(fileArray[i]);
                            File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID() + "/" + fileName), true);
                        }
                        if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID())))
                        {
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID()));
                        }
                        fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_Images"));
                        for (int i = 0; i < fileArray.Length; i++)
                        {
                            fileName = Path.GetFileName(fileArray[i]);
                            File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID() + "/" + fileName), true);
                        }
                        if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID())))
                        {
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID()));
                        }
                        fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_Logos"));
                        for (int i = 0; i < fileArray.Length; i++)
                        {
                            fileName = Path.GetFileName(fileArray[i]);
                            File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID() + "/" + fileName), true);
                        }
                        DataAccessObject.StaticClass.DeleteTemp();
                        Response.Redirect("ClubList.aspx");
                    }
                    else
                    {
                       //("حدث خطأ أثناء تعديل النادي");
                        return;
                    }
                }
                else
                {
                   //("يجب اختيارالنادي");
                    return;
                }
            }
            else
            {
                bool chkvalue = clubs.Add(club);
                if (chkvalue)
                {
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID())))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID()));
                    }
                    string fileName = null;
                    string[] fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_ColorImages"));
                    for (int i = 0; i < fileArray.Length; i++)
                    {
                        fileName = Path.GetFileName(fileArray[i]);
                        File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_ColorImages/" + GetID() + "/" + fileName), true);
                    }
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID())))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID()));
                    }
                    fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_Images"));
                    for (int i = 0; i < fileArray.Length; i++)
                    {
                        fileName = Path.GetFileName(fileArray[i]);
                        File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_Images/" + GetID() + "/" + fileName), true);
                    }
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID())))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID()));
                    }
                    fileArray = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/Temp/Club_Logos"));
                    for (int i = 0; i < fileArray.Length; i++)
                    {
                        fileName = Path.GetFileName(fileArray[i]);
                        File.Copy(fileArray[i], HttpContext.Current.Server.MapPath("~/images/Club_Logos/" + GetID() + "/" + fileName), true);
                    }
                    DataAccessObject.StaticClass.DeleteTemp();
                    Response.Redirect("ClubList.aspx");
                }
                else
                {
                    //("حدث خطأ أثناء اضافة النادي");
                    return;
                }
            }
        }

        private void RefreshList()
        {
            DataClassLayer.Statistic statistic = new DataClassLayer.Statistic();
            DataClassLayer.StatisticCollection statistics = new DataClassLayer.StatisticCollection();
            if (Request.QueryString["id"] != null &&
                Request.QueryString["id"].ToString() != "")
            {
                statistic.ClubID = int.Parse(Request.QueryString["id"].ToString());
            }
            DataTable table = statistics.FillList(statistic);
            if (table.Rows.Count > 0)
            {
                gvStatistics.DataSource = table;
                gvStatistics.DataBind();
            }
        }

        protected void imgbtnAdd_Click(object sender, ImageClickEventArgs e)
        {
            DataClassLayer.Statistic statistic = new DataClassLayer.Statistic();
            DataClassLayer.StatisticCollection statistics = new DataClassLayer.StatisticCollection();
            if (Request.QueryString["id"] != null &&
                Request.QueryString["id"].ToString() != "")
            {
                statistic.ClubID = int.Parse(Request.QueryString["id"].ToString());
            }
            else
            {
               //("يجب اختيار النادي");
                return;
            }
            if (CompareValidator.CanConvert(txtYear.Text, ValidationDataType.Integer))
            {
                statistic.Year = int.Parse(txtYear.Text);
            }
            else
            {
               //("السنة غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(txtWin.Text, ValidationDataType.Integer))
            {
                statistic.Win = int.Parse(txtWin.Text);
            }
            else
            {
               //("عدد حالات الفوز غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(txtDraw.Text, ValidationDataType.Integer))
            {
                statistic.Draw = int.Parse(txtDraw.Text);
            }
            else
            {
               //("عدد حالات التعادل غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(txtLose.Text, ValidationDataType.Integer))
            {
                statistic.Lose = int.Parse(txtLose.Text);
            }
            else
            {
               //("عدد حالات الخسارة غير صحيحة");
                return;
            }
            statistics.Add(statistic);
            RefreshList();
        }


        protected void gvStatistics_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvStatistics.EditIndex = e.NewEditIndex;
            RefreshList();
        }

        protected void gvStatistics_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            gvStatistics.EditIndex = -1;
            DataClassLayer.Statistic statistic = new DataClassLayer.Statistic();
            DataClassLayer.StatisticCollection statistics = new DataClassLayer.StatisticCollection();
            if (Request.QueryString["id"] != null &&
                Request.QueryString["id"].ToString() != "")
            {
                statistic.ClubID = int.Parse(Request.QueryString["id"].ToString());
            }
            else
            {
                //("يجب اختيار النادي");
                return;
            }

            if (CompareValidator.CanConvert(((Label)gvStatistics.Rows[e.RowIndex].FindControl("lblYear")).Text, ValidationDataType.Integer))
            {
                statistic.Year = int.Parse(((Label)gvStatistics.Rows[e.RowIndex].FindControl("lblYear")).Text);
            }
            else
            {
                //("السنة غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtWin")).Text, ValidationDataType.Integer))
            {
                statistic.Win = int.Parse(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtWin")).Text);
            }
            else
            {
                //("عدد حالات الفوز غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtDraw")).Text, ValidationDataType.Integer))
            {
                statistic.Draw = int.Parse(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtDraw")).Text);
            }
            else
            {
                //("عدد حالات التعادل غير صحيحة");
                return;
            }
            if (CompareValidator.CanConvert(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtLose")).Text, ValidationDataType.Integer))
            {
                statistic.Lose = int.Parse(((TextBox)gvStatistics.Rows[e.RowIndex].FindControl("txtLose")).Text);
            }
            else
            {
                //("عدد حالات الخسارة غير صحيحة");
                return;
            }
            statistic.ID = int.Parse(((LinkButton)gvStatistics.Rows[e.RowIndex].FindControl("lnkID")).Text.ToString());
            statistics.Edit(statistic);
            RefreshList();
            return;
        }

        protected void gvStatistics_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            gvStatistics.EditIndex = -1;
            DataClassLayer.Statistic statistic = new DataClassLayer.Statistic();
            DataClassLayer.StatisticCollection statistics = new DataClassLayer.StatisticCollection();
            statistic.ID = int.Parse(((LinkButton)gvStatistics.Rows[e.RowIndex].FindControl("LinkButton10")).CommandArgument.ToString());
            statistics.Delete(statistic);
            RefreshList();
        }

        protected void gvStatistics_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvStatistics.EditIndex = -1;
            RefreshList();
        }

        protected void btnUploadLogo_Click(object sender, EventArgs e)
        {
           string Thump_Name_File = "";
           DataAccessObject.StaticClass.UploadData(ref Logo, "~/images/temp/Club_Logos/", UploadLogo, ref Thump_Name_File);
           hfLogo.Value = Thump_Name_File;
           Logo.Visible = true;
        }
        private string GetID()
        {
            if (Request.QueryString["operation"] != null &&
                Request.QueryString["operation"].ToString() == "Edit")
            {
                if (Request.QueryString["id"] != null &&
                Request.QueryString["id"].ToString() != "")
                {
                    return Request.QueryString["id"].ToString();
                }
                else
                    return "";
            }
            else
            {
                DataClassLayer.Club club = new DataClassLayer.Club();
                DataClassLayer.ClubCollection clubs = new DataClassLayer.ClubCollection();
                return clubs.MaxID().ToString();
            }
        }

        protected void btnUploadColorImage_Click(object sender, EventArgs e)
        {
            string Thump_Name_File = "";
            DataAccessObject.StaticClass.UploadData(ref Color, "~/images/temp/Club_ColorImages/", UploadColor, ref Thump_Name_File);
            hfColorImage.Value = Thump_Name_File;
            Color.Visible = true;
        }

        protected void btnUploadClubImage_Click(object sender, EventArgs e)
        {
            string Thump_Name_File = "";
            DataAccessObject.StaticClass.UploadData(ref ClubImage, "~/images/temp/Club_Images/", UploadClubImage, ref Thump_Name_File);
            hfClubImage.Value = Thump_Name_File;
            ClubImage.Visible = true;
        }
    }
}